//
//  Emotion.swift
//  AnimotionKeyboard
//
//  Created by xxy on 16/6/2.
//  Copyright © 2016年 xxy. All rights reserved.
//

import UIKit

let EmoticonViewCellId = "EmoticonViewCellId"

/// 表情键盘视图
class EmotionView: UIView {
    private var selectedRmotionCallBack:(emotion: Emotion) -> Void
    
    // MARK: - 监听方法
    /// 点击工具栏 item
    @objc private func clickItem(item: UIBarButtonItem) {
       let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
       collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
        print("点我了")
    }
    
    
    // MARK: - 构造函数
    init(selectedEmoticon: (emoticon: Emotion) -> ()) {
        self.selectedRmotionCallBack = selectedEmoticon
        
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 216
        super.init(frame: rect)        //设置空间
        setupUI()
        //默认跳转到默认表情
         let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) {
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    /// 表情包数组
    private    lazy var packages = EmotionMangeger.sharedManager.packages
    /// 工具栏
    private lazy var toolbar = UIToolbar()
    /// 表情集合视图
    private lazy var collectionView = UICollectionView(frame: CGRectZero,
                                                       collectionViewLayout: EmoticonViewLayout())
    
    /// 表情键盘视图布局
    private class EmoticonViewLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            
            super.prepareLayout()
            let col: CGFloat = 7
            let row: CGFloat = 3
            let w =   collectionView!.bounds.width / col
            let margin = CGFloat(Int((collectionView!.bounds.height - row * w) * 0.5))
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
        }
    }
}

// MARK: - UICollectionViewDataSource
extension EmotionView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellId, forIndexPath: indexPath) as! EmotionCell
        cell.emotion = packages[indexPath.section].emoticons[indexPath.row]
        return cell
    }
    
    //点击选择事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let  em = packages[indexPath.section].emoticons[indexPath.row]
        selectedRmotionCallBack(emotion: em)
        
    }
    
}



// MARK: - 设置界面
private extension EmotionView {
    func setupUI() {
        //1:添加空间
        addSubview(collectionView)
        addSubview(toolbar)
        
        
        //2:设置约束
        //1>工具条
        toolbar.snp_makeConstraints { (make) in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(36)
            
        }
        //2->collectionView
        collectionView.snp_makeConstraints { (make) in
            make.top.equalTo(self.snp_top)
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(toolbar.snp_top)
            make.right.equalTo(self.snp_right)
        }
        //3>准备工具条
        prepareToolBar()
        prepareCollectionView()
        
    }
    
    func prepareToolBar() {
        tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        var index = 0
        
        for p in packages {
            
            let item = UIBarButtonItem(title:  p.group_name_cn, style: .Plain, target: self, action: #selector(EmotionView.clickItem(_:)))
            item.tag = index
            items.append(item)
            let  item2 = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target:  nil, action: nil)
            items.append(item2)
            index += 1
            
        }
        
        //删除最后一个
        items.removeLast()
        toolbar.items = items
        
    }
    
    ///collectionview数据准备
    func prepareCollectionView() {
        //注册cell
        collectionView.registerClass(EmotionCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        
        //指定数据源和代理
        collectionView.backgroundColor = UIColor.redColor()
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsHorizontalScrollIndicator = false
        
    }
}


// MARK: - 表情 Cell
private class EmotionCell: UICollectionViewCell {
    
    //表情
    var emotion: Emotion? {
        didSet {
            emotionBtn.setImage( UIImage(contentsOfFile: emotion!.imagePath)
                , forState: .Normal)
            emotionBtn.setTitle(emotion?.emoji, forState: .Normal)
            //是否是删除按钮
            if  emotion!.isRemoved {
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
                
            }
        }
    }
    
    // MARK: -搭建界面
    override  init(frame: CGRect) {
        
        super.init(frame: frame)
        contentView.addSubview(emotionBtn)
        emotionBtn.backgroundColor = UIColor.whiteColor()
        emotionBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        emotionBtn.frame = CGRectInset(bounds, 2, 2)
        emotionBtn.userInteractionEnabled = false
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    /// 表情按钮
    private lazy var emotionBtn: UIButton = UIButton()
}